package com.ultrapower.ctool.xn_app;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.model.ReWangGeFVO;
import com.ultrapower.ctool.model.RegisterRolePirVO;
import com.ultrapower.ctool.utils.InstanceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChangeJingYingActivity extends BaseActivity implements View.OnClickListener {
    private ChangeJingYingActivity changVo = this;
    private Button save;

    private Button cancle;

    private EditText entname;
    private EditText prname;
    private EditText prtel;
    private Spinner mainenttype;
    private Spinner enttype;
    private EditText encode;
    private EditText spissnum;
    private EditText address;
    private Spinner status;
    private AutoCompleteTextView insertowner;
    private EditText operation;
    private ArrayAdapter<RegisterRolePirVO> enttyperesaradapter;
    private CustomApplication application;
    //private JywgAutoCompleteAdater cursorAdapter;
    //private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    private Map<String, EditText> textMap = new HashMap<String, EditText>();
    private Map<String, Spinner> spinnerMap = new HashMap<String, Spinner>();
    private Map<String, Map<String, Object>> resultMap;
    public List<ReWangGeFVO> suggest=new ArrayList<ReWangGeFVO>();
    public ArrayAdapter<ReWangGeFVO> aAdapter;
    private AdapterView.OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long id) {
            System.out.println("--------------");
            ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
            ((TextView) parent.getChildAt(0)).setTextSize(18);
        }

        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(ChangeJingYingActivity.this, JingYingActivity.class);

                    startActivity(intent);
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "系统出现异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_jing_ying);
        save = (Button) findViewById(R.id.save_change);
        cancle = (Button) findViewById(R.id.cancle_change);
        ////
        entname = (EditText) findViewById(R.id.entname);
        textMap.put("entname", entname);
        prname = (EditText) findViewById(R.id.prname);
        textMap.put("prname", prname);
        prtel = (EditText) findViewById(R.id.prtel);
        textMap.put("prtel", prtel);
        encode = (EditText) findViewById(R.id.encode);
        textMap.put("encode", encode);
        spissnum = (EditText) findViewById(R.id.spissnum);
        textMap.put("spissnum", spissnum);
        address = (EditText) findViewById(R.id.address);
        textMap.put("address", address);
        insertowner = (AutoCompleteTextView) findViewById(R.id.insertowner);
        textMap.put("insertowner", insertowner);
        operation = (EditText) findViewById(R.id.operation);
        textMap.put("operation", operation);
        mainenttype = (Spinner) findViewById(R.id.mainenttype);
        spinnerMap.put("mainenttype", mainenttype);
        status = (Spinner) findViewById(R.id.status);
        spinnerMap.put("status", status);
        enttype = (Spinner) findViewById(R.id.enttype);
        spinnerMap.put("enttype", enttype);
        ///
        application = (CustomApplication) getApplication();
        save.setOnClickListener(this);
        cancle.setOnClickListener(this);
        Intent intent = getIntent();
        initData(intent.getStringExtra("dwid"));
       // cursorAdapter = new JywgAutoCompleteAdater(this, R.layout.simple_dropdown_item_1line, null, "cn", android.R.id.text1);
       /// insertowner.setThreshold(1);
      ///  insertowner.setAdapter(cursorAdapter);
        //suggest = new ArrayList<ReWangGeFVO>();
        insertowner.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable editable) {}
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String newText = s.toString();
                new ChangeJingYingActivity.getJson().execute(newText);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save_change:
                if ("".equals(entname.getText())
                        || "".equals(prname.getText())
                        || "".equals(prtel.getText())
                       // || "".equals(spissnum.getText())
                        || "".equals(encode.getText())
                        || "".equals(address.getText())
                        || suggest.size()<1
                        || "".equals(operation.getText())
                        || "".equals(((RegisterRolePirVO) mainenttype.getSelectedItem()).getId())
                        || "".equals(((RegisterRolePirVO) enttype.getSelectedItem()).getId())
                        || "".equals(((RegisterRolePirVO) status.getSelectedItem()).getId())
                        ) {
                    Toast.makeText(getApplicationContext(), "请完整参数", Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Response response = null;
                            try {
                                OkHttpClient client = new OkHttpClient();
                                //String _id = new DBHelper(changVo).queryBycn(entry.getValue().getText().toString());
                                FormBody.Builder builder = new FormBody.Builder()
                                        .add("userId", String.valueOf(application.getLoginUser().getLogin_id()));
                                for (Map.Entry<String, EditText> entry : textMap.entrySet()) {
                                    if ("insertowner".equals(entry.getKey())) {
                                        String id =  suggest.get(0).getId();
                                        System.out.println("----------------" + id);
                                        resultMap.get("result").put(entry.getKey(), id);
                                    } else {
                                        resultMap.get("result").put(entry.getKey(), entry.getValue().getText().toString());
                                    }
                                }
                                for (Map.Entry<String, Spinner> entry : spinnerMap.entrySet()) {
                                    resultMap.get("result").put(entry.getKey().split("_List")[0], ((RegisterRolePirVO) entry.getValue().getSelectedItem()).getId());
                                }
                                for (Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (entry.getValue() instanceof String) {
                                        builder.add(entry.getKey(), (String) entry.getValue());
                                    }
                                }
                                RequestBody requestBody = builder.build();
                                Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "form/doUpdate/c_aj_jydw").post(requestBody).build();
                                response = client.newCall(request).execute();
                                if (response.isSuccessful()) {//成功
                                    String result = response.body().string();
                                    System.out.println("result:" + result);
                                    Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                                    if ((boolean) resultMap.get("success")) {
                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);
                                    }
                                } else {
                                    Message message = new Message();
                                    message.what = 0;
                                    handler.sendMessage(message);
                                }
                            } catch (Exception e) {
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            } finally {
                                if (response != null) response.close();
                                ;
                            }
                        }
                    }).start();
                }

                break;
            case R.id.cancle_change:
//                Intent intent2 = new Intent(ChangeJingYingActivity.this, JingYingActivity.class);
//                startActivity(intent2);
                finish();
                break;
        }
    }

    //TODO 初始化化数据
    public void initData(final String dwid) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //status.setEnabled(false);
                    //status.setClickable(false);
                    //insertowner.setFocusable(false);
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .build();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "production/update/c_aj_jydw-" + dwid).post(requestBody).build();
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        resultMap = gson.fromJson(result, Map.class);
                        System.out.println(resultMap);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                for (final Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (textMap.get(entry.getKey()) != null) {
                                        textMap.get(entry.getKey()).setText(entry.getValue().toString());
                                        textMap.get(entry.getKey()).setEnabled ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));
                                        textMap.get(entry.getKey()).setFocusable ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));
                                    } else {
                                        if (entry.getKey().endsWith("_List") && entry.getValue() instanceof List) {
                                            List<Map<String, Object>> list = (List<Map<String, Object>>) entry.getValue();
                                            List<RegisterRolePirVO> voList = new ArrayList<RegisterRolePirVO>();
                                            for (Map<String, Object> value : list) {
                                                try {
                                                    value.put("id", String.valueOf(value.get("id")).split("\\.").length == 1 ? String.valueOf(value.get("id")) : String.valueOf(value.get("id")).split("\\.")[0]);
                                                    RegisterRolePirVO vo = (RegisterRolePirVO) InstanceUtil.mapToObject(value, RegisterRolePirVO.class);
                                                    voList.add(vo);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                            final Spinner spinner = spinnerMap.get(entry.getKey().split("_List")[0]);

                                            final ArrayAdapter<RegisterRolePirVO> aradapter = new ArrayAdapter<RegisterRolePirVO>(getApplicationContext(), android.R.layout.simple_spinner_item, voList);
                                           aradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);

                                            spinner.setAdapter(aradapter);
                                            final int k = aradapter.getCount();
                                            //System.out.println(aradapter.getItem(1).getId().toString());
                                            if (!"mainenttype".equals(entry.getKey().split("_List")[0])) {
                                                spinner.setOnItemSelectedListener(OnCatSpinnerCL);
                                            } else {
                                                mainenttype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                                    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                                                        ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
                                                        ((TextView) parent.getChildAt(0)).setTextSize(18);
                                                        RegisterRolePirVO item = (RegisterRolePirVO) mainenttype.getSelectedItem();
                                                        final String mainenttypeId = (String) item.getId();
                                                        if (mainenttypeId != null && !"".equals(mainenttypeId)) {
                                                            //生产单位分类
                                                            new Thread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    try {
                                                                        OkHttpClient client = new OkHttpClient();
                                                                        RequestBody enttypeRequestBody = new FormBody.Builder()
                                                                                .add("exp", "select tid ID, tname CN from dt_dwtype where tlevel=3 and ptid =" + mainenttypeId)
                                                                                .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                                                                                .build();
                                                                        Request enttypeRequest = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/comboJson").post(enttypeRequestBody).build();
                                                                        Response enttyperesponse = client.newCall(enttypeRequest).execute();
                                                                        if (enttyperesponse.isSuccessful()) {//成功
                                                                            String result = enttyperesponse.body().string();
                                                                            final List<RegisterRolePirVO> enttypereses = gson.fromJson(result, new TypeToken<List<RegisterRolePirVO>>() {
                                                                            }.getType());
                                                                            System.out.println(enttypereses);
                                                                            runOnUiThread(new Runnable() {
                                                                                @Override
                                                                                public void run() {
                                                                                    enttyperesaradapter = new ArrayAdapter<RegisterRolePirVO>(getApplicationContext(), android.R.layout.simple_spinner_item, enttypereses);
                                                                                    enttyperesaradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                                                                                    enttype.setAdapter(enttyperesaradapter);


                                                                                   enttype.setOnItemSelectedListener(OnCatSpinnerCL);
                                                                                    //enttype.setSelection(3);
                                                                                    for (int i = 0; i < enttyperesaradapter.getCount(); i++) {
                                                                                        if (resultMap.get("result").get("enttype").equals(enttyperesaradapter.getItem(i).getId().toString())) {
                                                                                            enttype.setSelection(i);
                                                                                            break;
                                                                                        }
                                                                                    }
                                                                                }
                                                                            });
                                                                        }

                                                                    } catch (Exception e) {
                                                                        e.printStackTrace();
                                                                    }
                                                                }
                                                            }).start();
                                                        }
                                                    }

                                                    public void onNothingSelected(AdapterView<?> parent) {
                                                    }
                                                });

                                            }
                                            for (int i = 0; i < k; i++) {
                                                if (resultMap.get("result").get(entry.getKey().split("_List")[0]).equals(aradapter.getItem(i).getId().toString())) {
                                                    spinner.setSelection(i);
                                                    break;
                                                }
                                            }
                                            //Map.Entry<String, Object> entry : resultMap.get("result").entrySet()
                                            for(Map.Entry<String, Spinner> entry1 : spinnerMap.entrySet()){
                                                entry1.getValue().setEnabled ((Boolean) resultMap.get("result").get(entry1.getKey()+"_qx"));
                                                entry1.getValue().setFocusable ((Boolean) resultMap.get("result").get(entry1.getKey()+"_qx"));
                                            }

                                        }
                                    }
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
            }
        }).start();
    }
    class getJson extends AsyncTask<String, String, String> {
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            aAdapter = new ArrayAdapter<ReWangGeFVO>(getApplicationContext(),R.layout.simple_dropdown_item_1line, suggest);
            //insertowner.setThreshold(1);
            insertowner.setAdapter(aAdapter);
            aAdapter.notifyDataSetChanged();
        }

        @Override
        protected String doInBackground(String... key) {
           // System.out.println(suggest);

            suggest.clear();
            Response response = null;
            if (key.length != 0 && !"".equals(key[0])) {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("field", "insertowner")
                            .add("code", "c_aj_jydw")
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .add("like", key.length == 0 ? "" : key[0])
                            .build();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/findLikeJson").post(requestBody).build();
                    response = client.newCall(request).execute();

                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();

                        suggest = gson.fromJson(result, new TypeToken<List<ReWangGeFVO>>() {
                        }.getType());
                        //System.out.println(suggest.size());
                    }
                } catch (Exception e) {
                    Log.w("Error", e.getMessage());
                }
            }
            return null;
        }

    }
}
